(function($) {
	function Cart() {
		this.acount = 0;
		this.totalMoney = 0;
		this.cartItems = [];
	};
	function CartItem() {
		this.id = 0;
		this.name = "";
		this.price = 0;
		this.number = 0;
		this.href="";
		this.img = "";
	};
	$.fn.mycart = function(settings){
		//初始化设置
		var setting = $.extend({},$.fn.mycart.defaults,settings);
		var orderBtnClick = $("."+setting.orderBtnClass).click(function(){
			var href = $(this).attr("href");
			var id = $(this).attr("id");
			var name = $(this).attr("name");
			var img = $(this).attr(setting.orderBtnImg);
			var price = $(this).attr(setting.orderBtnPrice);
			var cartItem = new CartItem();
			cartItem.id = id;
			cartItem.name = name;
			cartItem.price = parseFloat(price);
			cartItem.number = 1;
			cartItem.href = href;
			cartItem.img = img ;
			//添加
			fns.addToCart(cartItem);
		});
		var fns = {
			//添加购物车
			addToCart:function(cartItem){
				var cart = new Cart();
				cart = this.readFromCookie();
				var index = this.findById(cartItem.id ,cart);
				if( index == -1 ){ //如果不存在该项
					cart.cartItems.push(cartItem);
					cart.acount += parseInt(cartItem.number);
					cart.totalMoney += ((cartItem.price*10000)*cartItem.number)/10000;
					var itemHtml = this.generateItemHtml(cartItem);
					$("#cart .cart_content ul").children("li").remove(".empty");
					$("#cart .cart_content").children("ul").append(itemHtml);
				} else {
					var itemTemp = new CartItem();
					itemTemp = cart.cartItems[index];
					itemTemp.number += parseInt(cartItem.number);
					cart.totalMoney += ((cartItem.price*10000)*cartItem.number)/10000;
					cart.acount += parseInt(cartItem.number);
					var itemHtml = this.updateItemHtml(itemTemp);
					$("#cart .cart_content li#item_li_"+cartItem.id).html(itemHtml);
				}
				this.saveIntoCoockie(cart);
			},
			//删除购物车条目
			delFromCart:function (id) { //从购物车中移除该项
				var cart = new Cart();
				cart = this.readFromCookie();
				var index = this.findById(id , cart);
				if( index > -1){
					var cartItem = cart.cartItems[index];
					cart.acount -= parseInt(cartItem.number);
					cart.totalMoney -= ((parseFloat(cartItem.price)*10000)*cartItem.number)/10000;
					cart.cartItems.splice(index, 1);
				}
				this.saveIntoCoockie(cart);
			},
			//增加、减少  或 直接设置数量
			changeNumber:function(id ,type, number) { //点击加减按钮来改变该项的数量
				var cart = new Cart();
				cart = this.readFromCookie();
				var index = this.findById(id , cart);
				var cartItem = cart.cartItems[index];
				if( cartItem != null || cartItem != ""){
					if( type == "add") { //点击增加按钮
						cartItem.number++;
					} else if( type == "del"){ //点击减少按钮
						cartItem.number--;
						if( cartItem.number <= 0 ){//从购物车移除
							this.delFromCart(cartItem.id);
							return;
						}
					} else if( type == "set"){ //直接设置数量
						cartItem.number = number;
					}
				}
				this.saveIntoCoockie(cart);
			},
			//根据id查找
			findById:function (id ,cart){
				var index = -1;
				for(var i = 0;i < cart.cartItems.length; i++ ){
					if(cart.cartItems[i].id == id ){
						index = i;
						break;
					}
				}
				return index;
			},
			//生成购车条目html
			generateItemHtml:function(cartItem){
				var sb = new StringBuffer();
				sb.append("<li class=\"item_li\" id =\"item_li_").append(cartItem.id);
				sb.append("\">").append("<div class=\"item_li_img\">").append("<a href=\"").append(cartItem.href)
				.append("\"> <img src= \"").append(cartItem.img).append("\" /> </a> </div> <div class=\"item_li_info\"> <p class=\"item_name\"> <a title=\"")
				.append(cartItem.name).append("\" href=\"").append(cartItem.href).append("\" target=\"_blank\">").append(cartItem.name).append("</a> </p>");
				sb.append("<p class=\"item_price\"> <span class=\"item_price_span\"> <i>¥</i> <span>").append(cartItem.price)
				.append("</span> </span>").append("<b> x </b>").append(cartItem.number).append("</p> </div> </li>");
				//alert(sb.toString());
				//$("#cart .cart_content").children("ul").append(sb.toString());
				return sb.toString();
			},
			//更新购物车条目html
			updateItemHtml:function(cartItem){
				var sb = new StringBuffer();
				sb.append("<div class=\"item_li_img\">").append("<a href=\"").append(cartItem.href)
				.append("\"> <img src= \"").append(cartItem.img).append("\" /> </a> </div> <div class=\"item_li_info\"> <p class=\"item_name\"> <a title=\"")
				.append(cartItem.name).append("\" href=\"").append(cartItem.href).append("\" target=\"_blank\">").append(cartItem.name).append("</a> </p>");
				sb.append("<p class=\"item_price\"> <span class=\"item_price_span\"> <i>¥</i> <span>").append(cartItem.price)
				.append("</span> </span>").append("<b> x </b>").append(cartItem.number).append("</p> </div>");
				//alert(sb.toString());
				//$("#cart .cart_content li#item_li_"+cartItem.id).html(sb.toString());
				return sb.toString();
			},
			//保存到cookie
			saveIntoCoockie:function(cart){
				var values = [];
				var source ="";
				if( cart != null && cart != ""){
					for(var i= 0;i <cart.cartItems.length ;i++){
						var item = cart.cartItems[i];
						values.push(this.cartItemToString(item));
					}
					source = values.join("$$");
					$.cookie(setting.cookieFileName,source);
				}
			},
			//从cookie读取
			readFromCookie:function(){
				var source = $.cookie(setting.cookieFileName);
				var cart = new Cart();
				if( source == null || source == "") {
					return cart;
				} else {
					var items = source.split("$$");
					for(var i = 0;i < items.length ;i++){
						var item = items[i];
						var cartItem = new CartItem();
						cartItem = this.itemStringToObject(item);
						cart.cartItems.push(cartItem);
						cart.acount++;
						cart.totalMoney += cartItem.price*cartItem.number;
					}
					return cart;
				}
			},
			cartItemToString:function(cartItem){
				var result = [];
				result.push(cartItem.id);
				result.push(cartItem.name);
				result.push(cartItem.price);
				result.push(cartItem.number);
				result.push(cartItem.href);
				result.push(cartItem.img);
				/*
				result.append("{\"id\":").append(cartItem.id);
							result.append(",\"name\":").append(cartItem.name);
							result.append("\"price\":").append(cartItem.price);
							result.append(",\"number\":").append(cartItem.number);
							result.append("}");*/
				return result.join("||");
			},
			itemStringToObject:function(value){
				var itemValues = value.split("||");
				var cartItem = new CartItem();
				cartItem.id = itemValues[0];
				cartItem.name = itemValues[1];
				cartItem.price = parseFloat(itemValues[2]);
				cartItem.number = parseInt(itemValues[3]);
				cartItem.href = itemValues[4];
				cartItem.img = itemValues[5];
				return cartItem;
			}
		};
		var cart = fns.readFromCookie();
		//初始化页面购物车
		var sb = new StringBuffer();
		sb.append("<div class=\"wrap_cart_btn\"> <a href=\"#\"> <i class=\"minicart_ico\"> </i> <span>购物车</span> </a> <i class=\"minicart_gap\">|</i>")
		.append("<span class=\"minicart_num\">0</span> </div> <div class=\"cart_content\"> <ul>");
		if( cart.cartItems.length == 0 ){
			sb.append("<li class=\"empty\">您的购物车还是空的…</li>");
		} else {
			for ( var i =0; i < cart.cartItems.length ;i++){
				var cartItem = cart.cartItems[i];
				var itemstr = fns.generateItemHtml(cartItem);
				sb.append(itemstr);
			}
			//sb.append("<li class=\"go_cart\"> <a href=\"").append(setting.targetUrl).append("\" target=\"_blank\">去结算</a> </li>");
			$("#cart .cart_content").append("<div class=\"go_cart\"> <a href=\""+setting.targetUrl+"\" target=\"_blank\">去结算</a> </div>")
		}
		sb.append("</ul> </div>")
		$("#cart").html(sb.toString());
		//购物车滚动初始
		var start_pos = $("#cart").offset().top;
		$(window).scroll(function(){
		 var to_top = $(this).scrollTop();
		 var window_height = $(this).height();
		 var window_width = $(this).width();
		 $("#cart").animate({top:to_top+start_pos+"px"}, {queue:false,duration:500});
		});
	};
	//自定义StringBuffer，方便字符串拼接操作
	function StringBuffer(){
		this.content = new Array();
	};
	StringBuffer.prototype.append = function(value){
		this.content.push(value);
		return this;
	}
	StringBuffer.prototype.toString = function(){
		return this.content.join("");
	}
	//默认配置信息
	$.fn.mycart.defaults = {
		cookieFileName:"mycart",
		isCookie:true,
		orderBtnPrice:"price",		//购买按钮的price属性设置 
		orderBtnImg:"img",			//购买按钮的img属性设置 
		orderBtnClass:"",			//必须设置的 ,响应添加到购物车的按钮用<a href="" class="order_btn" id="01" name="瓜子" price="5" img="#"></a>,属性需要设置,所有类名同一标志 e.g: 物品列表的购买按钮
		tipMessage:"您的购物车还是空的",
		targetUrl:"#",				//必须设置的，当选购了商品后，点击 去结算 时要跳转的页面
		doSubmit:function(cart){}
	};
})(jQuery);